// 泛型

import {disconnect} from "cluster";

function echo<T>(arg: T): T {
    return arg
}

const result = echo('123')
console.log(result)

function swap<T, U>(tuple: [T,U]) : [U,T] {
 return [tuple[1],tuple[0]]
}
const result2 = swap(['122',123])
// result2[0].

// 2

function echoWithArr<T>(arg: T[]): T[] {
    console.log(arg.length)
    return  arg
}

const arrs = echoWithArr([1,2,3])

// 约束泛型

interface IWithLength {
  length: number
}

function echoWithLength<T extends IWithLength>(arg: T) : T {
    console.log(arg.length)
    return arg
}

const str = echoWithLength('123')
const obj = echoWithLength({'length': 123,width:123})
const arr = echoWithLength([1,2,3])


// 类
class Queue<T> {
    private data = []
    push(item: T) {
        return this.data.push(item)
    }
    pop(): T {
        return this.data.pop()
    }

}

const queue = new Queue<number>()
queue.push(1)
console.log(queue.pop().toFixed())

const queue1 = new Queue<string>()
queue1.push('123')
console.log(queue1.pop().length)

//接口
interface IKey<T,U> {
    name: T;
    age: U
}

let key1: IKey<string,number> = {'name':'123',age:2}
let key2: IKey<number,string> = {'name':20,age: '23'}


// 数组泛型
let arr1: number [] = [1,2,3]
let arr2: Array<number> = [1,2,3]

//用interface描述函数的类型
interface IAdd<T> {
    (a:T,b:T) : T
}


function add(a:number,b:number):number{
    return  a+ b
}

function add1(a:string,b:string):string {
    return a + b
}

let a:IAdd<number> = add
let b:IAdd<string> = add1
